package com.lilosoft.core.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5工具类
 *
 * @author qiusheng
 * @Date 2018-10-30
 */
public class MD5Utils {

	private MD5Utils() {
	}

	/**
	 * 生成注册码
	 * @param sourceStr 
	 * @return String
	 */
	public static String AuthCode(String sourceStr) {
		String result = "";
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(sourceStr.getBytes());
			byte[] b = md.digest();
			int i;
			StringBuffer buf = new StringBuffer("");
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0){
					i += 256;
				}
				if (i < 16){
					buf.append("0");
				}
				buf.append(Integer.toHexString(i));
			}
			result = buf.toString();
		} catch (NoSuchAlgorithmException e) {
//			LogUtils.error(e.getMessage());
		}
		return result;
	}

	/**
	 * 使用MD5加密
	 * 
	 * @param string
	 *            String
	 * @return String
	 */
	public static final String MD5(String string) {
		char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'A', 'B', 'C', 'D', 'E', 'F' };
		try {
			byte[] btInput = string.getBytes();
			// 获得MD5摘要算法的 MessageDigest 对象
			MessageDigest mdInst = MessageDigest.getInstance("MD5");
			// 使用指定的字节更新摘要
			mdInst.update(btInput);
			// 获得密文
			byte[] md = mdInst.digest();
			// 把密文转换成十六进制的字符串形式
			int j = md.length;
			char[] str = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str);
		} catch (Exception e) {
//			LogUtils.error(e.getMessage());
			return null;
		}
	}

	/**
	 * 可逆的加密算法
	 * 
	 * @param inStr 
	 * @return String
	 */
	public static String KL(String inStr) {
		char[] a = inStr.toCharArray();
		for (int i = 0; i < a.length; i++) {
			a[i] = (char) (a[i] ^ 'l');
		}
		String s = new String(a);
		return s;
	}

	/**
	 * 加密后解密
	 * 
	 * @param inStr 
	 * @return String
	 */
	public static String JM(String inStr) {
		char[] a = inStr.toCharArray();
		for (int i = 0; i < a.length; i++) {
			a[i] = (char) (a[i] ^ 'l');
		}
		String k = new String(a);
		return k;
	}

	public static void main(String[] args) {

		String startYear = MD5("2014-01-01");

//		LogUtils.info(startYear);

		String endYear = MD5("2099-12-31");

//		LogUtils.info(endYear);

		String s = new String("演示系统");
		System.out.println("原始：" + s);
		System.out.println("MD5后：" + MD5(s));
		//System.out.println("MD5后：" + AuthCode(s));
		System.out.println("MD5后再加密：" + KL(s));
		System.out.println("再加密：" + MD5(KL(s)));
		System.out.println("再加密16：" + MD5(KL(s)).substring(8, 24));
		System.out.println("解密为MD5后的：" + JM(KL("0")));

	}
}
